package com.rtline.business.listener;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.baomidou.mybatisplus.extension.service.IService;
import com.rtline.business.model.UserEntity;
import com.rtline.business.vo.BaseExcelVo;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>UserDataListener .
 *
 * <p>change history:
 *
 * <pre>
 * date         defect       person          comments
 * --------------------------------------------------------------------------------
 * 2025/5/31    ********     Tao Ren    create file.
 * </pre>
 *
 * @author Tao Ren
 * @date 2025/5/31 19:23
 */
@Slf4j
@Data
public class ExcelDataListener extends AnalysisEventListener<BaseExcelVo> {
    private final int batchSize = 1000; // 每1000条数据批量插入一次

    private final List<BaseExcelVo> dataList = new ArrayList<>();

    private final List<BaseExcelVo> allList = new ArrayList<>();

    private IService iService;

    private String importIdent;

    private boolean hasError = false; // 标志位，记录是否有错误数据

    private int successCount = 0;

    private int failCount = 0;

    private int totalCount = 0;

    public ExcelDataListener(IService iService) {
        this.iService = iService;
    }

    @Override
    public void invoke(BaseExcelVo data, AnalysisContext context) {
        totalCount++;
        //校验数据
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        Set<ConstraintViolation<BaseExcelVo>> violations = validator.validate(data);
        if (!violations.isEmpty()) {
            failCount++;
            hasError = true;
            StringBuilder sb = new StringBuilder();
            for (ConstraintViolation<BaseExcelVo> violation : violations) {
                sb.append(violation.getMessage()).append(";");
            }
            data.setErrorMessage(sb.toString());
        } else {
            successCount++;
            // 如果没有错误数据，处理入库
            dataList.add(data);
            if (dataList.size() >= batchSize) {
                saveData(); // 批量插入数据库
                dataList.clear();
            }
        }
        allList.add(data);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if (hasError) {
            // 如果已经有错误数据，直接跳过后续数据的处理
            return;
        }
        if (!dataList.isEmpty()) {
            saveData(); // 插入剩余数据
            dataList.clear();
        }
    }

    @SneakyThrows
    private void saveData() {

        // 在这里实现将dataList中的数据批量插入数据库的逻辑
        System.out.println("插入数据：" + dataList.size() + "条");

        List<UserEntity> entityList = ListUtils.newArrayList();
        for (BaseExcelVo userVo : dataList) {
            UserEntity userEntity = new UserEntity();
            BeanUtil.copyProperties(userVo, userEntity, false);
            entityList.add(userEntity);
        }
        boolean result = iService.saveOrUpdateBatch(entityList);
        log.info(StrUtil.format("UserDataListener execute saveData is {}", result));
    }
}
